package Hot100.Easy.LC94;

import java.util.ArrayList;
import java.util.Deque;
import java.util.LinkedList;
import java.util.List;

/**
 * 二叉树的中序遍历,递归
 */
public class LC94 {
    public static void main(String[] args) {
        TreeNode root=new TreeNode(1);
        root.right=new TreeNode(2);
        root.right.left=new TreeNode(3);
        System.out.println(inorderTraversal(root));
        System.out.println(inorderTraversal2(root));

    }

    //递归方法中顺序遍历二叉树
    public static List<Integer> inorderTraversal(TreeNode root) {
        ArrayList<Integer> res = new ArrayList<Integer>();
        inorder(res,root);
        return res;
    }

    static void inorder(ArrayList<Integer> res, TreeNode root) {
        if (root == null) return;
        else
            inorder(res,root.left);
            res.add(root.val);
            inorder(res,root.right);

    }

    //非递归方法：迭代，显式的维护一个栈，通过栈来遍历二叉树
    static List<Integer> inorderTraversal2(TreeNode root) {
        List<Integer> res=new ArrayList<>();
        Deque<TreeNode> stack=new LinkedList<>();
        while(root!=null || !stack.isEmpty()){
            while(root!=null){
                stack.push(root);
                root=root.left;
            }
            root=stack.pop();
            res.add(root.val);
            root=root.right;
        }
        return res;
    }
}
